package team.pwyseckill.service;

import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.pwyseckill.consts.RbmConsts;
import team.pwyseckill.mapper.CouponMapper;
import team.pwyseckill.mapper.GoodsMapper;
import team.pwyseckill.mapper.SeckillMapper;
import team.pwyseckill.pojo.entity.Coupon;
import team.pwyseckill.pojo.entity.Goods;
import team.pwyseckill.pojo.entity.Seckill;

import java.util.*;

@Service
@Transactional
public class SeckillServiceImpl {
    @Resource
    private CouponMapper couponMapper;

    @Resource
    private SeckillMapper seckillMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private RedisTemplate redisTemplate;

    //保存秒杀优惠卷
    @RabbitHandler
    @RabbitListener(queues = RbmConsts.SEC_QUEUE)
    @Async
    public void saveOrd(Map<String, Object> maps) {
        Integer userId = (Integer) maps.get("userId");
        Integer secId = (Integer) maps.get("secId");
        Seckill seckill = seckillMapper.findBySeckillId(secId);
        Goods goods = goodsMapper.findByGoodsId(seckill.getGoodsId());
        Coupon coupon = new Coupon();
        coupon.setMoney(goods.getMoney());
        coupon.setUserId(userId);
        coupon.setIllustrate(goods.getDetails());
        Date date = new Date();
        coupon.setCreatedTime(date);

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, 1);
        coupon.setUpdatedBy(cal.getTime());
        coupon.setActiveId(1);
        coupon.setStatus(0);
        couponMapper.add(coupon);

        //秒杀表库存减一
        seckillMapper.updateNumber(secId);
    }

    //    活动开始
    @RabbitHandler
    @RabbitListener(queues = RbmConsts.SECKILL_EX_QUEUE)
    @Async
    public void lodingSeckill(Map<String, Integer> map) {
        ValueOperations vop = redisTemplate.opsForValue();
        Integer seckillId = map.get("seckillId");
        Integer status = map.get("status");
        if (status == 0) {
            //            活动开始
            vop.set("sec_status_" + seckillId, "1");
            seckillMapper.updateActiveStatusById(seckillId);
        } else if (status == 1) {
            //            活动结束
            vop.set("sec_status_" + seckillId, "2");
            seckillMapper.updateEndStatus(seckillId);
        }
    }

}
